#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

/**
 *  Writes "hello world" in the given file 
 * 
 *  name    file_hello_world.c
 *  version 1.0
 *  author  Prof. Dr.-Ing. Damian Weber (dweber@htw-saarland.de)
 */
int main(int numberOfArguments, char **arguments)
{
  if(numberOfArguments <= 1)
  {
    return 1;
  }
  
  /* Opens or creates a file for reading or writing. If successful, open() returns a non-negative integer, termed a file
     descriptor. It returns -1 on failure, and sets errno to indicate the error. */
  int fileDescriptor =  open(arguments[1],       /* file name */
                             O_CREAT | O_WRONLY, /* O_CREAT  - create file if it does not exist 
                                                    O_WRONLY - open for writing only 
                                                    The bitwise or-operation "|"  allows to combine both. */
                             S_IRUSR | S_IWUSR); /* chmod-flags: The file is created with the given chmod-flags AND (!!!) 
						    modified by the umask process
		                                    S_IRUSR 0000400    R for owner
						    S_IWUSR 0000200    W for owner
                                                    => chmod sets "rw-" for owner by the created file (don't forget umask!) */
  if(fileDescriptor < 0)
  {
    perror("open()");
    return 1;
  }

  /* Writes "hello world\n" (12 bytes) to the file referenced by fileDescriptor. On success it returns the number of bytes which are 
     written. Otherwise a -1 is returned and the global variable errno is set. */
  if(write(fileDescriptor, "hello world\n", 12) < 0)
  {
    perror("write()");
    return 1;
  }

  /* The close() function deletes "fileDesciptor" and  returns the value 0 if successful; otherwise close() returns the value -1 
     and sets the global variable errno.*/
  if(close(fileDescriptor) < 0)
  {
    perror("close()");
    return 1;
  }

  return 0;
}